<?php

namespace app\result;

use app\model\user\UserSetting;

class UserSettingResult extends BaseResult
{
    public static function action($user_id, $key, $value)
    {
        if (is_array($value) || is_object($value)) {
            $value = json_encode($value, JSON_UNESCAPED_UNICODE);
        }
        $model = new UserSetting();
        $hasId = $model->get_value(['user_id' => $user_id, 'bs_key' => $key], 'id');
        if ($hasId) {
            $model->data_update(['id' => $hasId], ['bs_value' => $value]);
        } else {
            $model->data_add(['user_id' => $user_id, 'bs_key' => $key, 'bs_value' => $value]);
        }
        return self::success_return('设置成功');
    }

    public static function get($user_id, $key)
    {
        $model = new UserSetting();
        $value = $model->get_value(['user_id' => $user_id, 'bs_key' => $key], 'bs_value');
        if ($value) {
            //判断是不是json
            $json_obj = @json_decode($value, true);
            if ($json_obj && json_last_error() == JSON_ERROR_NONE) {
                $value = $json_obj;
            }
        }
        return $value;
    }

    //个性化配置
    public static function get_diy_action_config($user_id)
    {
        $bs_key = 'diy_action_config';
        $baseSet = [
            ['key' => 'bill_action_continue', 'label' => '账单连续录入', 'value' => false],
            ['key' => 'enable_amount_type', 'label' => '启用收支方式', 'value' => true],
            ['key' => 'enable_budget', 'label' => '启用预算', 'value' => false],
            ['key' => 'enable_cashbook', 'label' => '启用账本', 'value' => false],
            ['key' => 'enable_bill_cycle', 'label' => '周期循环', 'value' => false],
        ];
        $value = self::get($user_id, $bs_key);
        if (!$value) {
            self::action($user_id, $bs_key, $baseSet);
        } else {
            if (count($value) !== count($baseSet)) {
                $baseSet = array_column($baseSet, null, 'key');
                $valueKeys = array_column($value, 'key');
                foreach ($baseSet as $key => $item) {
                    if (!in_array($key, $valueKeys)) {
                        $value[] = $item;
                    }
                }
                self::action($user_id, $bs_key, $value);
            }
        }
        $value = self::get($user_id, $bs_key);

        return self::success_return('success', [
            'list' => $value
        ]);

    }

    public static function setting_set($user_id, $args, $bs_key)
    {
        $data = $args['list'] ?? [];
        if (!$data) {
            return self::error_return('请选择要设置的项');
        }
        $list = [];
        foreach ($data as $item) {
            $list[] = [
                'key' => $item['key'],
                'label' => $item['label'],
                'value' => boolval($item['value'])
            ];
        }
        self::action($user_id, $bs_key, $list);
        return self::success_return('保存成功', $list);
    }
}
